<?php

namespace App\Models\Steel;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class SteelArchive extends Model
{
    protected $table = 'steel_archive';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    /**
     *获取列表
     */
    public static function getList(Request $request, $cpid, $status = 0, $isgetall = 0)
    {
        $query = self::where(['cpid' => $cpid])->orderBy('archive_no', 'asc');
        if (in_array($status, [1, 2])) {
            $query->where('status', $status);
        }
        $archive_no = $request->archive_no;
        if ($archive_no != '') {
            $query->where('archive_no', 'like', '%' . $archive_no . '%');
        }

        $archive_name = $request->archive_name;
        if ($archive_name != '') {
            $query->where('archive_name', 'like', '%' . $archive_name . '%');
        }

        $archive_spec = $request->archive_spec;
        if ($archive_spec != '') {
            $query->where('archive_spec',  'like', '%' .$archive_spec. '%');
        }

        $type_name = $request->type_name;
        if ($type_name != '') {
            $query->where('type_name', $type_name);
        }

        $breed_name = $request->breed_name;
        if ($breed_name != '') {
            $query->where('breed_name', $breed_name);
        }

        $material_name = $request->material_name;
        if ($material_name != '') {
            $query->where('material_name',  'like', '%' .$material_name. '%');
        }

        $steel_factory_name = $request->steel_factory_name;
        if ($steel_factory_name != '') {
            $query->where('steel_factory_name', $steel_factory_name);
        }

        // 如果需要去重
        $is_distinct = $request->is_distinct ?? 0;
        if ($is_distinct) {
            $query->groupBy('archive_spec');
        }

        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->select(['id', 'cpid', 'archive_spec', 'archive_no', 'archive_name', 'type_id','subtype_id', 'breed_id', 'material_id', 'steel_factory_id', 'archive_type', 'type_name', 'subtype_name', 'type_no', 'subtype_no', 'breed_name', 'material_name', 'steel_factory_name', 'status'])
                ->paginate($limit)->toArray();
            return paginateDataToArray($list);
        } else {
            $list = $query->select(['id', 'cpid', 'archive_spec', 'archive_no', 'archive_name', 'type_id','subtype_id', 'breed_id', 'material_id', 'steel_factory_id', 'archive_type', 'type_name', 'subtype_name',  'type_no', 'subtype_no', 'breed_name', 'material_name', 'steel_factory_name', 'status'])
                ->get()->toArray();
            return ['list' => $list];
        }
    }
}
